package org.example.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Java的JSON工具类
 */
public class JsonUtils {
    public static String JsonStringify(Object person) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.writeValueAsString(person);
        } catch (JsonProcessingException e) {
            System.out.println(e.getMessage());
            return "";
        }
    }

    public static <T> T JsonParse(String jsonString, Class<T> Person) {
        try {
            // 创建一个 ObjectMapper 实例
            ObjectMapper objectMapper = new ObjectMapper();

            // 将 JSON 字符串反序列化为 Java 对象

            return objectMapper.readValue(jsonString, Person);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return null;
        }
    }

    public static class Test {
        public static void JsonParse() {
            Person person = JsonUtils.JsonParse("{\"name\":\"ScorpioDong\",\"age\":20}", Person.class);
            System.out.println(person.getName());
            System.out.println(person.getAge());
        }

        public static void JsonStringify() {
            Person person = new Person("ScorpioDong", 20);
            System.out.println(JsonUtils.JsonStringify(person));
        }

        // 定义一个简单的 Java 类
        public static class Person {
            private String name;
            private int age;

            public Person() {
            }

            public Person(String name, int age) {
                this.name = name;
                this.age = age;
            }

            // Getter 和 Setter 方法
            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public int getAge() {
                return age;
            }

            public void setAge(int age) {
                this.age = age;
            }
        }
    }
}
